<!-- 半成品类型管理 -->
<template>
  <BaseMainSlot>
    <!-- 这页面 -->
    <template v-slot:zhactbar>
      <ActionBar
        :page-no="101"
        :add-active="addActive"
        :del-active="delActive"
        :cancel-active="cancelActive"
        :has-edit="false"
        :has-cancel="false"
        :has-save="false"
        :save-active="saveActive"
        :has-fasong="true"
        fasong-text="agricultureType"
        @fasong="examine"
        @add="add"
        @cancel="cancel"
        @del="del"
      />
      <!-- <el-button
        class="examine"
        @click="examine"
      > 半成品类型提交 </el-button> -->
    </template>
    <template v-slot:boxleft>
      <div class="zhtabletitle">已有半成品类型</div>
      <div>
        <!-- TODO: -->
        <!-- check-strictly -->
        <el-tree
          ref="treeOne"
          :props="treerule"
          show-checkbox
          :data="treeDataOne"
          highlight-current
          node-key="materialTypeNo"
          @check-change="handleSelectionChange"
        />
      </div>
      <!-- <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="calc(100% - 80px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="materialTypeName" label="半成品类型名称" />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.materialTypeNo" slot-scope="scope">
            <el-button
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row.materialTypeNo)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table> -->
      <!-- <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      /> -->
    </template>
    <template v-slot:boxright>
      <div class="zhtabletitle">所有半成品类型</div>
      <div>
        <el-tree
          ref="treeTwo"
          :props="treerule"
          show-checkbox
          :data="treeDataTwo"
          highlight-current
          node-key="materialTypeNo"
          @check-change="handleSelectionChangetwo"
        />
      </div>
      <!-- <el-table
        v-loading="loadingtwo"
        highlight-current-row
        :data="tableDatatwo"
        stripe
        border
        height="calc(100% - 80px)"
        @selection-change="handleSelectionChangetwo"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="materialTypeName" label="半成品类型名称" />
      </el-table>
      <Pagination
        :page-size="pageSizetwo"
        :current-page="currentPagetwo"
        :total-size="totalSizetwo"
        @changePageSize="changePageSizetwo"
        @changeCurrentPage="changeCurrentPagetwo"
      /> -->
    </template>
    <template v-slot:dig>
      <!-- 新增业务组件的弹框 -->
      <dialogds
        title="半成品类型"
        :visible="dialogExamineFormVisible"
        @close="close"
        @titlebtn="titlebtn"
      >
        <template v-slot:form>
          <el-form
            ref="ExamineForm"
            label-position="left"
            :model="ExamineForm"
            class="el-form"
          >
            <el-form-item
              label="归属:"
              prop="parentNo"
              class="w50p"
            >
              <el-select
                v-model="ExamineForm.parentNo"
                filterable
                clearable
                class="selcect-one"
              >
                <el-option
                  v-for="(comitem, comindex) in categoryTypeList"
                  :key="comindex"
                  :value="comitem.materialTypeNo"
                  :label="comitem.materialTypeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :rules="[{
                message: '半成品类型名称不能为空',
                trigger: 'blur',
                required: true
              }]"
              label="半成品类型名称:"
              prop="materialTypeName"
              class="w50p"
            >
              <el-input
                v-model="ExamineForm.materialTypeName"
                clearable
              />
            </el-form-item>
            <!-- <el-form-item label="种养图片:" prop="pictureNo" class="w100p">
              <ele-upload-image
                v-model="image"
                multiple
                :response-fn="handleResponse"
                :before-remove="handleRemove"
                :headers="headers"
                :file-size="10"
                :action="ImageUrl()"
              />
            </el-form-item> -->
          </el-form>
          <!-- <div>
          </div> -->
        </template>
        <template v-slot:btn>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="savemes"
          >提 交</el-button>
        </template>
        <template v-slot:table>
          <el-input
            v-model="esname"
            style="margin-bottom: 10px;width: 30%;"
            placeholder="输入名称查询"
            clearable
            @input="titlebtn(2)"
          />
          <el-table
            highlight-current-row
            :data="ExamineTable"
            stripe
            border
            height="calc(100% - 90px)"
          >
            <el-table-column
              type="index"
              label="序号"
              width="100"
            />
            <el-table-column
              prop="parentName"
              label="归属"
            />
            <el-table-column
              prop="materialTypeName"
              label="半成品类型"
            />
            <el-table-column
              prop="reason"
              label="原因"
            >
              <template slot-scope="scope">
                {{ scope.row.reason || '————' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="applyStatus"
              label="状态"
            >
              <template slot-scope="scope">
                <span
                  v-if="scope.row.applyStatus === 1"
                  style="color: yellow;font-weight: 600;"
                > 审核中</span>
                <span
                  v-if="scope.row.applyStatus === 0"
                  style="color: green;font-weight: 600;"
                > 通过</span>
                <span
                  v-if="scope.row.applyStatus === 2"
                  style="color: red;font-weight: 600;"
                > 审核不通过</span>
              </template>
            </el-table-column>
            <el-table-column
              width="200"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  class="text-btn-cursor"
                  type="text"
                  :disabled="scope.row.applyStatus !== 1"
                  size="small"
                  style="height: 15px"
                  @click="Examineedit(scope.row)"
                ><i class="el-icon-edit-outline"></i>修 改</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </dialogds>
      <el-dialog
        title="提示"
        :visible.sync="dialogExaminesVisible"
        width="50%"
      >
        <el-form
          ref="ExamineForms"
          label-position="left"
          :model="ExamineForms"
          class="el-form"
        >
          <el-form-item
            label="归属:"
            prop="parentNo"
            class="w50p"
          >
            <el-select
              v-model="ExamineForms.parentNo"
              filterable
              clearable
              class="selcect-one"
            >
              <el-option
                v-for="(comitem, comindex) in categoryTypeList"
                :key="comindex"
                :value="comitem.materialTypeNo"
                :label="comitem.materialTypeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :rules="[{
              message: '半成品类型名称不能为空',
              trigger: 'blur',
              required: true
            }]"
            label="半成品类型名称:"
            prop="materialTypeName"
            class="w50p"
          >
            <el-input
              v-model="ExamineForms.materialTypeName"
              clearable
            />
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            class="zh-button-one"
            @click="dialogExaminesVisible = false"
          >取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="savees"
          >确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar/index";
// import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/basic-info-manage/agr-source-Type-Manage";
import dialogds from "../component/dialog.vue";
import BaseMainSlot from "@/components/BaseMainSlot/basezuoyou.vue";
import { mymixin } from "@/utils/mixins";
// import { getToken } from '@/utils/auth';
export default {
  name: "AgrSourceTypeManage",
  components: { ActionBar, BaseMainSlot, dialogds },
  mixins: [mymixin],
  data() {
    return {
      // ----表格二号----
      loadingtwo: true,
      // 当前页
      currentPagetwo: 1,
      // 每页的数据条数
      pageSizetwo: 10,
      // 总条数
      totalSizetwo: 0,
      treerule: {
        children: "child",
        label: "materialTypeName"
      },
      treeDataOne: [],
      // 表格二号数据
      treeDataTwo: [],
      tableData: [],
      // 表格二号数据
      tableDatatwo: [],
      // 是否能输入
      // -------
      canInput: false,
      rules: {},
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      dialogExamineFormVisible: false,
      categoryTypeList: [],
      dialogExaminesVisible: false,
      ExamineForms: {}
    };
  },
  watch: {},
  created() {
    this.getTableDataListone();
    // 获取表格数据
    this.getTableDataListtwo();
  },
  mounted() {
    this.getSelect();
  },
  methods: {
    examine() {
      this.dialogExamineFormVisible = true;
      // this.$refs['ExamineForm'].resetFields();
    },
    savemes() {
      this.$refs["ExamineForm"].validate(valid => {
        if (valid) {
          if (!this.ExamineForm.parentNo) {
            this.ExamineForm.parentNo = 0;
          }
          let param = {
            ...this.ExamineForm,
            applyStatus: 1,
            organizationNo: sessionStorage.organizationNo,
            farming: 'PLANT',
            semiProductType: true
          };
          nowpagereq.addListES(param).then(response => {
            let mes = response;
            if (mes.code === 1) {
              this.$message.success("提交成功！");
              this.ExamineForm = {};
              this.$refs["ExamineForm"].resetFields();
              // this.gettabledataList()
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    Examineedit(e) {
      this.ExamineForms = { ...e };
      this.dialogExaminesVisible = true;
    },
    savees() {
      this.$refs["ExamineForms"].validate(valid => {
        if (valid) {
          if (!this.ExamineForms.parentNo) {
            this.ExamineForms.parentNo = 0;
          }
          let param = {
            ...this.ExamineForms,
            farming: 'PLANT',
            semiProductType: true
          };
          nowpagereq.editListES(param).then(response => {
            let mes = response;
            if (mes.code === 1) {
              this.$message.success("修改成功！");
              this.ExamineForms = {};
              this.$refs["ExamineForms"].resetFields();
              this.dialogExaminesVisible = false;
              // this.gettabledataList()
              this.titlebtn(2);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    close(e) {
      this.dialogExamineFormVisible = e;
    },
    titlebtn(e) {
      if (e === 2) {
        let params = {
          // page: this.currentPage,
          // size: this.pageSize,
          // entity: {
          //   unitName: this.unitName
          // }
          materialTypeName: this.esname || undefined,
          farming: 'PLANT',
          semiProductType: true
        };
        nowpagereq.getListES(params).then(response => {
          let mes = response.data;
          if (response.code === 1) {
            this.ExamineTable = mes;
            this.resetActionBar();
          } else {
            this.$message.warning("获取表格失败");
          }
        });
      }
    },
    // 获取当前拥有类型表格
    getTableDataListone() {
      this.loading = true;
      nowpagereq.getFarmingAssetList({
        semiProductType: true
      }).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("当前半成品类型表格获取失败");
        }
        // let data = res.data;
        // // 赋值总条数
        // this.totalSize = data.totalElements;
        // 赋值数组
        this.treeDataOne = res.data;
        // this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
        this.addActive = false;
      });
    },
    // 获取所有半成品类型表格
    getTableDataListtwo() {
      this.loadingtwo = true;
      nowpagereq
        .getAllBasicList({
          isPlantSystemFlag: true,
          farming: 'PLANT',
          semiProductType: true
        })
        .then(res => {
          this.loadingtwo = false;
          if (res.code === 0) {
            this.$message.error("所有半成品类型表格获取失败");
          }
          // let data = res.data;
          // 赋值总条数
          this.treeDataTwo = res.data;
          console.log(res.data,'res');
          // this.totalSizetwo = data.totalElements;
          // // 赋值数组
          // this.tableDatatwo = data.content;

          // let havline = this.tableDatatwo.length % this.pageSizetwo
          // if (this.tableDatatwo.length < this.pageSizetwo) {
          //   if (havline < this.pageSizetwo) {
          //     const remain = this.pageSizetwo - havline;
          //     for (var i = 0; i < remain; i++) {
          //       this.tableDatatwo.push({ 'indflag': i + this.tableDatatwo.length - 1 });
          //     }
          //   }
          // }

          this.resetActionBar();
          this.addActive = false;
        });
    },
    async getSelect() {
      const { data: ress } = await nowpagereq.queryByCondition({
        organizationNo: sessionStorage.organizationNo,
        isPlantSystemFlag: true,
        farming: 'PLANT',
        semiProductType: true
      });
      this.categoryTypeList = ress;
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    changePageSizetwo(pageSize) {
      this.pageSizetwo = pageSize;
      this.getTableDataListtwo();
    },
    changeCurrentPagetwo(currentPage) {
      this.currentPagetwo = currentPage;
      this.getTableDataListtwo();
    },
    // TODO:
    handleSelectionChange() {
      let list = this.$refs.treeOne.getCheckedKeys();
      console.log(list,'删除');
      this.nowselectedList = [];
      this.nowselectedList = list;
      if (this.nowselectedList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    handleSelectionChangetwo(data) {
      // 整理原始数据
      let originArr = []
      this.treeDataOne.forEach(el => {
        originArr.push(el.materialTypeNo)
        el.child.forEach((it)=>{
          originArr.push(it.materialTypeNo)
        })
      });
      // 整理添加数据
      this.nowselectedTwoList = [];
      let list = this.$refs.treeTwo.getCheckedKeys(false,true);
      let addArr = []
      addArr=[...list,...this.$refs.treeTwo.getHalfCheckedKeys()]
      addArr.forEach(el=>{
        if(!originArr.includes(el)) {
          this.nowselectedTwoList.push(el)
        }
      })
      if (this.nowselectedTwoList && this.nowselectedTwoList.length > 0) { this.addActive = true; } else this.addActive = false;
    },
    // TODO:删除
    delmessage() {
      // this.$confirm('是否删除半成品类别？', '删除半成品类型', {
      //   distinguishCancelAndClose: true,
      //   confirmButtonClass: 'btnFalses',
      //   confirmButtonText: '删除',
      //   cancelButtonText: '取消删除'
      // }).then(() => {
      nowpagereq.delList(this.nowselectedList).then(res => {
        if (res.code === 1) {
          this.$message.success("删除成功");
          this.getTableDataListone();
        } else {
          this.$message.error("删除失败");
        }
      });
      // })
    },
    handleDelete(no) {
      this.$confirm("是否删除半成品类型？", "删除半成品类型", {
        distinguishCancelAndClose: true,
        confirmButtonClass: "btnFalses",
        confirmButtonText: "删除",
        cancelButtonText: "取消删除"
      })
        .then(() => {
          nowpagereq.delList([no]).then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataListone();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(action => {
          // this.$message({
          //   type: 'info',
          //   message: action === 'cancel'
          //     ? '取消删除'
          //     : '停留在当前页面'
          // })
        });
    },
    add() {
      nowpagereq.addList(this.nowselectedTwoList).then(res => {
        if (res.code === 1) {
          this.getTableDataListone();
          this.$message.success("添加成功");
        } else {
          this.$message.error("添加失败");
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}
// ::v-deep .el-message-box__wrapper {
//       background: red !important;
//   .el-message-box {
//     .btnFalses {
//       background: red !important;
//     }
//   }
// }
</style>
